package fun.stgoder.test1;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class TestPhaser {
    public static void main(String[] args) {

        Phaser phaser = new Phaser() {
            @Override
            public boolean onAdvance(int phase, int registeredParties) {
                switch (phase) {
                    case 0:
                        System.out.println("all reach a " + registeredParties);
                        return false;
                    case 1:
                        System.out.println("all reach b " + registeredParties);
                        return false;
                    case 2:
                        System.out.println("all reach c " + registeredParties);
                        return false;
                }
                return registeredParties == 0;
            }
        };
        phaser.bulkRegister(5);

        for (int i = 0; i < 5; i++) {
            final int j = i;
            new Thread(() -> {
                System.out.println(j + " reach a");
                phaser.arriveAndAwaitAdvance();

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(j + " reach b");
                phaser.arriveAndAwaitAdvance();

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(j + " reach c");
                phaser.arriveAndAwaitAdvance();


            }).start();
        }
    }
}
